;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Sales.ServiceBorrowIn", [])
        .controller("ServiceBorrowInCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$timeout", "EventBus", "$filter", "UserContextService", "$stateParams", "MaterialService", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $timeout, EventBus, $filter, UserContextService, $stateParams, MaterialService) {
            $scope.activeFlag = [true, false, false, false, false];
            $scope.markInfo = {
                allCheckedBill: false,
                allCheckedMaterial: false,
                curRow: -1
            };
            $scope.deleteIdList = [];
            $scope.borrowId = "";
            $scope.submitted = false;
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.condition = {};
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false,
                showMateriel: false
            };
            $scope.dataList = [];
            $scope.tabFlag = {};
            var tabFlag = {
                0: "详情",
                1: "新增",
                2: "编辑",
                3: "入库"
            };
            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/serviceBorrowIn/export"),
                sectionParam: {ids: []},
                allUrl: ybHttp.RequestUrl("device", "/serviceBorrowIn/exportAll")
            };
            $scope.orderObj = {
                detailVOList: []
            };
            $scope.tableConfig = {
                fixedWidth: 205,
                scrollWidth: 1400,
                tableCol: [
                    {
                        type: "",
                        name: "退回单号",
                        dataField: "borrowInNo",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单人",
                        dataField: "createName",
                        width: 60,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单时间",
                        dataField: "createDateStr",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "借用单号",
                        dataField: "borrowOutNo",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "服务人员",
                        dataField: "serviceStaffName",
                        width: 60,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "退回仓库",
                        dataField: "warehouseCode",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "退回单状态",
                        dataField: "statusStr",
                        width: 60,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 180,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };

            $scope.materielTableConfig = {
                scrollWidth: 1910,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 100,
                        dataField: "materialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 200,
                        dataField: "materialsDes",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单位",
                        width: 80,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "本单已退回",
                        width: 80,
                        dataField: "thisReturnQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "退回数量",
                        width: 80,
                        dataField: "returnQty",
                        input: true,
                        inputType: "num"
                    },
                    {
                        name: "借用单出库数量",
                        width: 80,
                        dataField: "borrowOutboundQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "转销售数量",
                        width: 80,
                        dataField: "resaleQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "借用单已退回",
                        width: 80,
                        dataField: "borrowReturnQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单价",
                        width: 100,
                        dataField: "price",
                        input: false,
                        inputType: ""
                    }
                ]
            };

            // 出库零件table信息
            $scope.outMaterielTbConfig = {
                scrollWidth: 1910,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 100,
                        dataField: "materialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单位",
                        width: 40,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "本单已退回",
                        width: 60,
                        dataField: "thisReturnQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "储位",
                        width: 180,
                        dataField: "locationCode",
                        input: true,
                        inputType: "func"
                    },
                    {
                        name: "退回数量",
                        width: 40,
                        dataField: "returnQty",
                        input: false,
                        inputType: "num"
                    },
                    {
                        name: "借用单出库数量",
                        width: 80,
                        dataField: "borrowOutboundQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "转销售数量",
                        width: 80,
                        dataField: "resaleQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "借用单已退回",
                        width: 80,
                        dataField: "borrowReturnQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单价",
                        width: 100,
                        dataField: "price",
                        input: false,
                        inputType: ""
                    }
                ]
            };

            // 退回单按钮的权限code
            var btnPermissionCode = {
                serviceBorrowInExport: window.ActionCode.serviceBorrowInExport,
                serviceBorrowInEdit: window.ActionCode.serviceBorrowInEdit,
                serviceBorrowInReceive: window.ActionCode.serviceBorrowInReceive,
                serviceBorrowInPrint: window.ActionCode.serviceBorrowInPrint,
                serviceBorrowInFinish: window.ActionCode.serviceBorrowInFinish,
                serviceBorrowInDelete: window.ActionCode.serviceBorrowInDelete
            };

            // 退回单按钮的权限
            $scope.btnPermission = {
                serviceBorrowInExport: true,
                serviceBorrowInEdit: true,
                serviceBorrowInReceive: true,
                serviceBorrowInPrint: true,
                serviceBorrowInFinish: true,
                serviceBorrowInDelete: true
            };

            // 查看用户的按钮权限
            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    billFixedWidth: {left: $scope.tableConfig.fixedWidth + "px"}
                };
            };

            // 切换tab
            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                $scope.deleteIdList = [];  // 清空要删除的零件id数组
                switch (index) {
                    case 0:
                        initData();
                        getDataList();
                        $scope.submitted = false;
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    default:
                        break;
                }
            };

            // 初始化数据
            function initData() {
                $scope.tabFlag = {};
                $scope.orderObj = {
                    headerInfo: {},
                    detailVOList: []
                };
                $scope.markInfo.allCheckedMaterial = false;
                $scope.toolbarConfig.showMateriel = false;
            }

            // 选择储位
            $scope.multiSelDepot = function () {
                var warehouseCode = $scope.orderObj.serviceBorrowInVO.warehouseCode;
                var list = $scope.orderObj.detailVOList;
                MaterialService.multiSelDepot(warehouseCode, list);
            };

            // 选择储位
            $scope.selDepot = function (item) {
                var param = {
                    warehouseCode: $scope.orderObj.serviceBorrowInVO.warehouseCode
                };
                ybWidget.DepotSelector(param).then(function (data) {
                    item.warehouseCode = data.warehouseCode;
                    item.areaCode = data.areaCode;
                    item.locationCode = data.locationCode;
                })
            };

            // 清除储位
            $scope.clearDepot = function (item) {
                item.warehouseCode = "";
                item.areaCode = "";
                item.locationCode = "";
            };

            // 请求退回单数据列表
            function getDataList(curPage) {
                // 每次请求数据清空要导出的退回单id数组
                $scope.exportParam.sectionParam.ids = [];
                var service = "device";
                var reqUrl = "/serviceBorrowIn/list";
                //遍历搜索条件对象里的空值并删除  不然搜索不出数据
                Object.keys($scope.condition).forEach(function (key) {
                    if (!$scope.condition[key]) delete $scope.condition[key];
                });
                var param = {
                    pageSize: $scope.pageInfo.pageSize,
                    pageNum: curPage || $scope.pageInfo.curPage,
                    filters: $scope.condition
                };
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.createDateStr = $filter("YbDate")(item.createDate, 'yyyy-MM-dd HH:mm:ss');
                        item.statusStr = $filter("ProgressStatus")(item.status, "inDepot");
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                    return resp.value.list;
                });
            }

            // 点击列的事件
            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        $scope.tabFlag = {
                            type: 0,
                            name: tabFlag[0]
                        };
                        viewDetail(item);
                        break;
                    default:
                        break;
                }
            };

            $scope.toSort = function (config, index) {
                ybWidget.ToSort(config, index);
            };

            // 展示和隐藏高级搜索
            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            // 打印订单
            $scope.printBill = function (item) {
                var param = {
                    billId: [item.id],
                    printType: "ServiceBorrowIn"
                };
                ybWidget.SetIsPrintOrPreview(param);
            };

            // 搜索退回单列表
            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            // 重置搜索条件
            $scope.reset = function () {
                $scope.condition = {};
            };

            // 修改数量时 修改总计
            $scope.setTotalPrice = function () {
                var total = 0;
                angular.forEach($scope.orderObj.detailVOList, function (item) {
                    item.totalPrice = $filter("decimalCover")(ybWidget.Times(item.returnQty, item.price), 2);
                    total = ybWidget.Plus(total, parseFloat(item.totalPrice));
                });
                $scope.orderObj.serviceBorrowInVO.totalPrice = total;
            };

            // 删除零件接口
            function deleteMateriel (ids) {
                var url = "/serviceBorrowInDetail/delete";
                return ybHttp.Post('device', url, ids).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return false;
                    }
                    return true;
                })
            }

            // 零件單個刪除
            $scope.delMateriel = function (index) {
                // 如果是编辑需要把id放到deleteIdList  提交的时候放入参数中
                if ($scope.orderObj.serviceBorrowInVO.id) {
                    var id = $scope.orderObj.detailVOList[index].id;
                    $scope.deleteIdList.indexOf(id) < 0 && $scope.deleteIdList.push(id);
                }
                $scope.orderObj.detailVOList.splice(index, 1);
            };

            // 批量删除零件
            $scope.batchDelMateriel = function () {
                var selectedCount = 0;
                var ids = [];
                for (var i = 0, len = $scope.orderObj.detailVOList.length; i < len; i++) {
                    if (!!$scope.orderObj.detailVOList[i].isChecked) {
                        selectedCount++;
                        ids.push($scope.orderObj.detailVOList[i].id);
                    }
                }
                if (!selectedCount) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                // 如果是编辑需要把id放到deleteIdList  提交的时候放入参数中
                if ($scope.orderObj.serviceBorrowInVO.id) {
                    $scope.deleteIdList = ids;
                }
                batchDeleteM();
            };

            // 循环遍历删除零件
            function batchDeleteM() {
                for (var i = $scope.orderObj.detailVOList.length - 1; i >= 0; i--) {
                    if (!!$scope.orderObj.detailVOList[i].isChecked) {
                        $scope.orderObj.detailVOList.splice(i, 1);
                    }
                }
                if ($scope.orderObj.detailVOList.length === 0) {
                    $scope.markInfo.allCheckedMaterial = false;
                }
            }

            // 批量删除借用退回单
            $scope.batchDelBorrowIn = function () {
                var deleteList = [];      // 要删除的退回单id数组
                angular.forEach($scope.dataList, function (item) {
                    // 只有状态为未入库的借用单才能删除
                    if (item.isChecked && item.status === 0) {
                        deleteList.push(item.id);
                    }
                });
                if (deleteList.length === 0) {
                    ybWidget.ShowMessage('请选择可删除数据', MESG_TYPE.Error);
                    return;
                }
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    deleteBorrowInService(deleteList).then(function (res) {
                        if (res) {
                            ybWidget.ShowToaster('success', '操作成功');
                            $scope.markInfo.allCheckedList = false;
                            getDataList();
                        }
                    });
                })
            };

            // 编辑借用单
            $scope.editBorrowIn = function (item) {
                getBorrowItemDetail(item).then(function (data) {
                    if (data) {
                        $scope.tabFlag.type = 2;
                        $scope.tabFlag.name = tabFlag[2];
                        $scope.changeTab(2);
                    }
                })
            }

            // 单个删除借用退回单
            $scope.delBorrowIn = function (id) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    deleteBorrowInService([id]).then(function (res) {
                        if (res) {
                            ybWidget.ShowToaster('success', '操作成功');
                            getDataList();
                        }
                    });
                })
            };

            // 调用删除借用退回单接口
            function deleteBorrowInService (ids) {
                var url = '/serviceBorrowIn/delete';
                return ybHttp.Post('device', url, ids).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return false;
                    }
                    return true;
                })
            }

            // 查看详情
            function viewDetail (item) {
                getBorrowItemDetail(item).then(function (data) {
                    if (data) {
                        $scope.changeTab(3);
                    }
                });
            }

            // 获取借用单详情
            function getBorrowItemDetail(item) {
                var url = '/serviceBorrowIn/item';
                var param = {
                    id: item.id
                };
                return ybHttp.Get('device', url, param).then(function(res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return false; 
                    }
                    res.value.serviceBorrowInVO.statusStr = $filter("ProgressStatus")(res.value.serviceBorrowInVO.status, "inDepot");
                    $scope.orderObj = res.value;
                    return true;
                })
            }

            // 入库
            $scope.receive = function (item) {
                getBorrowItemDetail(item).then(function (data) {
                    if (data) {
                        $scope.tabFlag = {
                            type: 3,
                            name : tabFlag[3]
                        };
                        $scope.changeTab(3);
                    }
                })
            }

            // 确认入库 
            $scope.confirmReceive = function () {
                if (checkLocationCode()) {
                    return;
                }
                ybWidget.ShowMessage("确定要入库吗？", MESG_TYPE.Ask).then(function () {
                    var url = "/warehouseInboundRecord/receive";
                    var headerInfo = {
                        businessOrder: $scope.orderObj.serviceBorrowInVO.borrowInNo
                    };
                    var params = {
                        detailList: $scope.orderObj.detailVOList,
                        headerInfo: headerInfo
                    };
                    ybHttp.Post('device', url, params).then(function (res) {
                        if (res.code !== 0) {
                            ybWidget.ShowMessage(res, MESG_TYPE.Error);
                            return false;
                        }
                        ybWidget.ShowToaster('success', '入库成功');
                        $scope.changeTab(0);
                    })
                })
            }

            function checkLocationCode () {
                var bole = false;
                angular.forEach($scope.orderObj.detailVOList, function (item) {
                    // 把materialsNo 转为 materialNo， 入库接口只认识materialNo
                    item.materialNo = item.materialsNo;
                    if (!item.locationCode) {
                        item.locationErr = true;
                        bole = true;
                    }
                });
                return bole;
            }

            // 完结整个订单
            $scope.finishBillAll = function (borrowInNo) {
                ybWidget.ShowMessage("确定要完结订单吗？", MESG_TYPE.Ask).then(function () {
                    $scope.finishBill(borrowInNo).then(function (data) {
                        data && getDataList();
                    });
                })
            }

            // 借用退回单某个零件的结单
            $scope.finishBill = function (borrowInNo, materialsNo, index) {
                var url = '/serviceBorrowIn/manualFinish';
                var params = {
                    billNo: borrowInNo
                };
                if (materialsNo) {
                    params.materialsNo = materialsNo;
                }
                ybHttp.Post('device', url, params).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return false;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    if (index >= 0) {
                        $scope.orderObj.detailVOList[index].status = 3;
                    }
                    getDataList();
                    return true;
                })
            }

            //服务借用单转借用有退回单 新增
            $scope.saveData = function (invalid) {
                if (!invalid) {
                    $scope.submitted = true;
                    return;
                }
                if ($scope.orderObj.detailVOList.length === 0) {
                    ybWidget.ShowMessage("零件不可为空", MESG_TYPE.Error);
                    return;
                }
                //检查列表数据是否合法  不合法则不保存
                if (!checkValid()) {
                    return;
                }
                var service = "device";
                var reqUrl = "/serviceBorrowIn/add";
                var param = angular.copy($scope.orderObj);
                if ($scope.deleteIdList.length > 0) {
                    param.deleteIdList = $scope.deleteIdList;
                }
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                });
            };

            function checkValid () {
                var bole = true;
                var maxCount = 0;
                angular.forEach($scope.orderObj.detailVOList, function (item) {
                    maxCount = parseFloat(item.borrowOutboundQty) - parseFloat(item.resaleQty) - parseFloat(item.borrowReturnQty);
                    if (!item.returnQty || parseFloat(item.returnQty) <= 0)  {
                        item.qtyErr = true;
                        item.qtyErrMsg = "退回数量不能为空和0";
                        bole = false;
                    } else if (parseFloat(item.returnQty) > maxCount) {
                        item.qtyErr = true;
                        item.qtyErrMsg = "退回数量已超出借用剩余数量";
                        bole = false;
                    }
                });
                return bole;
            }

            $scope.cancel = function () {
                $scope.changeTab(0);
            };

            $scope.actionUrl = ybHttp.RequestUrl("device", "/threeGuaranteesPur/download");

            function getBillIds() {
                $scope.exportParam.sectionParam.ids = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.ids.push(item.id);
                    }
                });
            }

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectSingle = function (item, list, type) {
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    if (!checkAll(list)) {
                        $scope.markInfo["allChecked" + type] = false;
                    } else {
                        $scope.markInfo["allChecked" + type] = true;
                    }
                }
                getBillIds();
            };

            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    if (type == 'Material' && item.status !== 0) {
                        item.isChecked = false;
                    } else {
                        item.isChecked = $scope.markInfo["allChecked" + type];
                    }
                });
                getBillIds();
            };

            // 通过借用单号来查详情
            function getBorrowDetail(billId) {
                var service = "device";
                var reqUrl = "/serviceBorrowIn/borrowingData";
                var param = {
                    borrowOutNo: billId
                };
                return ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    $scope.orderObj = resp.value;
                    $scope.tabFlag.type = 1;
                    $scope.tabFlag.name = tabFlag[1];
                    $scope.changeTab(2);
                    return resp.value;
                });
            };

            $scope.selectWarehouse = function () {
                ybWidget.WarehouseUsingSelector().then(function (data) {
                    $scope.orderObj.serviceBorrowInVO.warehouseCode = data.warehouseCode;
                })
            };
            $scope.viewImage = function (item) {
                console.log(item)
                ybWidget.ViewImage({
                    FileUrl: item
                })
            };

            $scope.clearWarehouse = function () {
                $scope.orderObj.serviceBorrowInVO.warehouseCode = "";
            };

            (function () {
                // 从服务借用单跳转过来
                if (!!$stateParams.borrowId) {
                    getBorrowDetail($stateParams.borrowId)
                }
                getDataList();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }])
    ;
})(window, window.angular);
